package com.lanou3g.zjl.chating.utils;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.ImageView;

import com.lanou3g.zjl.chating.volley.VolleySingleton;
import com.parse.ParseObject;
import com.parse.ParseQuery;

/**
 * Created by dllo on 15/12/4.
 */
public class GetUserAvatarHelper extends AsyncTask<String, Integer, String> {

    public Context context;
    private VolleySingleton volleySingleton;//网络请求单例
    private ImageView imageView;//设置头像的控件
    private String username;//用户名
    private Handler handler;

    public GetUserAvatarHelper(Context context, ImageView imageView, String username) {

        this.context = context;
        this.imageView = imageView;
        this.username = username;
        volleySingleton = VolleySingleton.getInstance(context);
    }

    public GetUserAvatarHelper(Context context,Handler h) {

        this.context = context;
        volleySingleton = VolleySingleton.getInstance(context);
        handler = h;
    }
    @Override
    protected String doInBackground(String... strings) {
        //后台进行头像的地址获取
        username = strings[0];
        ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("UserSet");
        pQuery.whereEqualTo("username", username);
        ParseObject pUser = null;
        try {
            pUser = pQuery.getFirst();
            if (pUser.getParseFile("avatar").getUrl() != null) {

                String url = pUser.getParseFile("avatar").getUrl();
                if (!TextUtils.isEmpty(url)) {
                    if (handler != null){
                        Message message = handler.obtainMessage();
                        message.obj = url;
                        handler.sendMessage(message);
                    }
                    return url;
                }
            }
        } catch (com.parse.ParseException e) {

        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (s != null && imageView != null) {
            volleySingleton.getPic(s, imageView);//前台进行头像设置
        }
    }
}
